package com.sql.parser.lineage.pg;

import com.sql.parser.lineage.utils.ReplaceTokenUtils;
import mysql.MySqlParser;
import mysql.MySqlParserBaseListener;
import org.antlr.v4.runtime.TokenStreamRewriter;

public class PgCreateIndexTranslateListener extends MySqlParserBaseListener {
    protected TokenStreamRewriter rewriter;

    public PgCreateIndexTranslateListener(TokenStreamRewriter rewriter) {
        this.rewriter = rewriter;
    }

    @Override
    public void exitCreateIndex(MySqlParser.CreateIndexContext ctx) {
        // 1、处理索引名称
        MySqlParser.EngineNameContext indexContext = ctx.uid().simpleId().engineName();
        String indexName = "";
        if (null != indexContext) {
            indexName = ReplaceTokenUtils.replaceBackQuote(indexContext.getText(), indexContext, rewriter);
        }
        // 2、处理表名
        MySqlParser.EngineNameContext tableNameContext = ctx.tableName().fullId().uid().get(0).simpleId().engineName();
        if (null != tableNameContext) {
            ReplaceTokenUtils.replaceBackQuote(tableNameContext.getText(), tableNameContext, rewriter);
        }

        // 3、处理索引所在字段名称
        String indexColumnName = ctx.indexColumnNames().getText();
        indexColumnName = indexColumnName.replace("`", "\"");
        rewriter.delete(ctx.indexColumnNames().getStart(), ctx.indexColumnNames().getStop());
        if (!ctx.getStop().getText().contains(";")) {
            rewriter.insertAfter(ctx.getStop(), indexColumnName + ";");
        } else {
            rewriter.insertAfter(ctx.getStop(), indexColumnName);
        }
        // 4、处理USING BTREE 或者 COMMENT
        for (MySqlParser.IndexOptionContext indexOption : ctx.indexOption()) {
            // 索引类型变小写 可设置大小写无关 暂不处理
            if ("USING".equalsIgnoreCase(indexOption.getStart().getText())) {

            } else if ("COMMENT".equalsIgnoreCase(indexOption.getStart().getText())) {
                // 处理备注 先删除再生成pg备注语法，备注内容必须被单引号包裹
                rewriter.delete(indexOption.getStart(), indexOption.getStop());
                String commentContent = indexOption.getStop().getText();
                if (commentContent.startsWith("\"")) {
                    commentContent = commentContent.replace("\"", "`");
                }
                String comment = "\nCOMMENT ON INDEX " + indexName + " IS " + commentContent;
                rewriter.insertAfter(ctx.getStop(), comment);
            }
        }
    }
}
